package net.matt2000.android.search.wp;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Looper;
import android.os.ParcelFileDescriptor;
import android.util.DisplayMetrics;
import android.view.WindowManager;

public class IconProvider extends ContentProvider {

	private static final int XHDPI_ICON_SIZE = 104; //inferred
	private static final int HDPI_ICON_SIZE = 78; //measured in the emulator
	private static final int MDPI_ICON_SIZE = 52; //measured in the emulator
	private static final int LDPI_ICON_SIZE = 36; //inferred
	private static final String START_BY_PIXEL_SIZE = "\\d+px-.*";
	private static final int DEFAULT_ICON_SIZE = 50;

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public String getType(Uri uri) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean onCreate() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public ParcelFileDescriptor openFile(Uri uri, String mode) {
    	ParcelFileDescriptor parcel = null;
    	if (Looper.myLooper() == Looper.getMainLooper()) //if in the main thread we can't load images
    		return parcel;
    	try {
    		String url = Uri.decode(uri.getPath().substring(1));
//    		url = changeIconSize(url); //adapt thumbnail size to screen dpi
//            URL imageUrl = new URL (url);
//            String fileName="temp";
//            File file = new File(getContext().getCacheDir(), fileName);
//            FileOutputStream fos = new FileOutputStream(file);
//            try {
//            	InputStream is = imageUrl.openStream();
//        		byte[] b = new byte[2048];
//        		int length;
//        		while ((length = is.read(b)) != -1) {
//        			fos.write(b, 0, length);
//        		}
//				fos.close();
//				is.close();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//			}
			//downloading a pefectly sized image takes too long,
			// so instead we download a 50px image (default), quadruple its size and let Android resize it correctly
			URL imageUrl = new URL (url);
			String fileName="temp";
			File file = new File(getContext().getCacheDir(), fileName);
			FileOutputStream fos = new FileOutputStream(file);
			Bitmap img = BitmapFactory.decodeStream(imageUrl.openStream());
			//quadruple the size because small images are not upscaled
			if (img.getWidth()<=50 && img.getHeight()<=50) //some images aren't downscaled by default, you don't want to upscale them
				img = Bitmap.createScaledBitmap(img, img.getWidth()*4, img.getHeight()*4, false);
			img.compress(CompressFormat.PNG, 100, fos);
            parcel = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
    	} catch (FileNotFoundException e) {
			// ignore
		} catch (IOException e) {
			// ignore
		}

		return parcel;
	}
	
	@SuppressWarnings("unused")
	private String changeIconSize (String url) {
		String fileName = url.substring(url.lastIndexOf('/')+1);
		if (fileName.matches(START_BY_PIXEL_SIZE)) {
			//the file name starts by a default size, we change it to the icon size
			int iconSize = DEFAULT_ICON_SIZE;
			DisplayMetrics metrics = new DisplayMetrics(); 
			((WindowManager)getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metrics); 
			switch(metrics.densityDpi){ 
			     case DisplayMetrics.DENSITY_LOW: 
			         iconSize = LDPI_ICON_SIZE;       
			    	 break; 
			     case DisplayMetrics.DENSITY_MEDIUM: 
			         iconSize = MDPI_ICON_SIZE;       
			    	 break; 
			     case DisplayMetrics.DENSITY_HIGH: 
			         iconSize = HDPI_ICON_SIZE;
			    	 break;
			     default:
			    	 iconSize = XHDPI_ICON_SIZE;
			}
			fileName = iconSize+fileName.substring(fileName.indexOf('p'));
			return url.substring(0, url.lastIndexOf('/')+1)+fileName;
		}
		return url;
	}


}
